<template>
	<view>
		<!-- <z-nav-bar backState="2000" title=""></z-nav-bar> -->
		<!-- 自定义导航栏 -->
		<z-nav-bar v-if="!isShow && !isWxBrowser" :scrollTop="scrollTop" transparentFixedFontColor="#000" type="transparentFixed"  backState="2000" title="蜂恋"></z-nav-bar>
		<view v-show="!isShow" class="" id="c">
			<view class="h-bg" :style="'background-image: url('+headBgImg+');'">
				<view class="box-item flex align-item">
					<!-- <image class="dingwei" :src="imgUrl + 'static/web/icon/dingwei.png'" mode=""></image>
					<view class="chengshi">
						{{ address }}
					</view> -->
					<u-search placeholder="搜索" v-model="keyword" :show-action="false" bgColor="#FFFFFF" placeholderColor="#BDC5D4" @search="search()"></u-search>
				</view>
				<!-- 公共组件-每个页面必须引入 -->
				<public-module></public-module>
				<!-- banner -->
				<view class="banner_swiper_box">
					<swiper class="banner_swiper" :autoplay="true" :interval="5000" circular previous-margin="30px" next-margin="30px" :duration="1000" @change="onSwiperChange">
						<swiper-item v-for="(item, index) of bannerList" :key="index">
							<view class="banner_img" :class="{ active: swiperIndex == index }">
								<image :src="item.image" mode="aspectFill" @click="onBanner(item)"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<view class="video_box" v-if="videoShow" @click="onCloseVideo"><video :src="videoUrl" autoplay="true" controls></video></view>
			</view>
			<view class="main">
				<view class="flex j-between align-item bt">
					<view class="bt-left">
						<image class="bt-left-img" :src="imgUrl + '/static/web/img/yuanfen.png'" mode=""></image>
						<view class="bt-left-txt">
							心动就在一瞬间～
						</view>
					</view>
					<view class="bt-right flex align-item" @click="goSearch">
						<view>
							筛选
						</view>
						<view style="margin: 0 10rpx;">
							{{ searchLength == 0 ? '' : ' · ' + searchLength }}
						</view>
						<image class="bt-right-icon" :src="imgUrl + '/static/web/img/jiantou.png'" mode=""></image>
					</view>
				</view>
				
				<!-- 瀑布流 -->
				<view class="waterfall-box h-flex-x h-flex-2">
					<view>
						<helang-waterfall 
							v-for="(item,index) in leftList" 
							:key="index" 
							:params="item" 
							tag="left"
							:index="index"
							@height="onHeight"
							@click="onClick"
							@collection="collection"
						></helang-waterfall>
					</view>
					<view>
						<helang-waterfall 
							v-for="(item,index) in rightList" 
							:key="index" 
							:params="item" 
							@height="onHeight"
							@click="onClick"
							tag="right"
							:index="index"
							@collection="collection"
						></helang-waterfall>
					</view>
				</view>
				<view class="load-txt">{{ajax.loadTxt}}</view>
			</view>
			
		</view>
		<view class="hn" @click="goHongniang">
			<image :src="imgUrl + 'static/web/img/hn.png'" mode=""></image>
		</view>
		<!-- 启动页广告 -->
		<view class="start_adv" v-if="isShow && startPage">
			<image class="adv_img" :src="startPage" mode=""></image>
			<view class="down">
				{{i}}
			</view>
		</view>
		<!-- 启动页广告-->
		<!-- 首页广告开始 -->
		<view v-if="(!isShow && !uid && homeAdvData['image']) || (!isShow && userData.length == 0 && homeAdvData['image'])">
			<u-overlay :show="homeAdvShow">
					<view class="home_adv flex align-item column">
						<image class="home_adv-img" :src="homeAdvData.image" mode=""></image>
						<view class="home_adv-tit" @click="onBanner(homeAdvData)">
							完善资料
						</view>
						<image class="home_adv-icon" :src="imgUrl + 'static/web/icon/chacha.png'" mode="" @click="guanbi()"></image>
					</view>
			</u-overlay>
		</view>
		<!-- 首页广告结束 -->
		<!-- #ifdef MP-WEIXIN -->
		<tab-bar  v-show="!isShow" :current="0"></tab-bar>
		<!-- #endif -->
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
// #ifdef MP-WEIXIN
import {onLogin} from '@/config/login';
// #endif
// #ifdef H5
import {h5Login} from '../../config/html5Utils.js';
// #endif
import helangWaterfall from "@/uni_modules/helang-waterfall/components/helang-waterfall/helang-waterfall.vue"

export default {
	data() {
		return {
			imgUrl: this.$http.baseUrl, // 服务器域名
			headBgImg: this.$http.baseUrl + 'static/web/img/apply-bg.png', // 顶部背景图片
			uid: '', // 用户id
			videoUrl: '',
			videoShow: false,
			swiperIndex: 0,
			bannerList: [1, 1, 1, 1],
			loadStatus: 'loadmore',
			// 图片瀑布流
			leftHeight: 0,
			rightHeight: 0,
			leftList: [],
			rightList: [],
			ajax: {
				// 是否可以加载
				load: true,
				// 加载中提示文字
				loadTxt: '',
				// 每页的请求条件
				limit:10,
				// 页码
				page:1,
			},
			isShow: false, //控制启动广告显示隐藏
			i: 6, //倒计时初始值
			startPage: '', // 启动页广告图
			searchData: {}, // 搜索条件--搜索页
			searchLength: 0, // 搜索条件长度--搜索页
			keyword: '', // 搜索条件--顶部搜索框
			onePage: 0, //存储是不是第一次进入首页
			scrollTop: 0, // 顶部导航栏类型
			homeAdvShow: false, // 首页广告页显示隐藏
			homeAdvData: [], // 存储首页广告
			userData: [], // 存储我发布的信息
			address: '', // 定位
		};
	},
	computed: {
		...mapState(['userInfo']),
	},
	//第一次加载
	onLoad(options) {
		// this.getLocation()
		this.onePage = 1
		//小程序码是否带有参数
		if(options && options.scene){
			//params转 obj  字符串参数  a=123&b=456 转 {a:"123",b:"456"}
			var query = this.getRequestParameters(decodeURIComponent(options.scene))
			uni.setStorageSync('p_id', query.p_id);
		}
		this.getStartPage()
		if(!uni.getStorageSync('storage_key')){
			this.showStartAdv()
		}
		this.getBanner()
		this.getHomeAdv()
		// #ifdef MP-WEIXIN
		// onLogin(() => {
		// 	this.getCoupon();
		// });
		uni.hideTabBar()
		// #endif
		this.getList();
		var that = this
		uni.$on('updateData', function(data) {
			that.searchData = data
			that.searchLength = Object.keys(data).length
			that.leftHeight = 0
			that.rightHeight = 0
			that.ajax.page = 1;
			that.leftList = []
			that.rightList = []
			that.getList();
		})
		uni.$on('refresh', function() {
			that.leftHeight = 0
			that.rightHeight = 0
			that.ajax.page = 1;
			that.leftList = []
			that.rightList = []
			that.getList();
		})
	},
	//页面显示
	onShow() {
		var that = this
		var userInfo = this.$store.state.userInfo
		that.uid = userInfo.uid;
		if(userInfo.uid){
			that.getMyReleaseData()
		}else{
			that.homeAdvShow = true
		}
	},
	components: {
		"helang-waterfall": helangWaterfall
	},
	// 监听滑动事件
	onPageScroll(e) {
		this.scrollTop = e.scrollTop
	},
	onReady() {
		
	},
	// 触底触发
	onReachBottom() {
		this.getList();
	},
	// 下拉刷新
	onPullDownRefresh(){
		// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
		setTimeout(()=>{
			this.ajax.page = 1;
			this.leftHeight = 0;
			this.rightHeight = 0;
			this.ajax.load = true;
			this.getList();
		},800);
	},
	//方法
	methods: {
		...mapMutations(['setWebViewUrl']),
		pageData() {},
		onPageJump(url) {
			uni.navigateTo({
				url: url
			});
		},
		// 刷新
		shuaxincopy(a,b){
			var that = this
			if(a == 'right'){
				if(that.rightList[b].is_collection == 1){
					that.rightList[b].is_collection = 0
				}else{
					that.rightList[b].is_collection = 1
				}
			}else if(a == 'left'){
				if(that.leftList[b].is_collection == 1){
					that.leftList[b].is_collection = 0
				}else{
					that.leftList[b].is_collection = 1
				}
			}
		},
		// params转 obj  字符串参数
		// 例子： a=1&b=2 => {a:1,b:2}
		getRequestParameters(params="") {
			let theRequest = new Object();
			if (params != undefined) {
				let strs = params.split("&");
				for (let i = 0; i < strs.length; i++) {
					theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
				}
			}
			return theRequest;
		},
		// 获取轮播图
		getBanner(){
			var that = this
			that.$http.get('api/ZhBanner/index',{
				'type':1
			}).then(res => {
					if(res){
						that.bannerList = res.list
					}
				});
		},
		// 获取启动页
		getStartPage(){
			var that = this
			that.$http.get('api/ZhBanner/index',{
				'type':0
			}).then(res => {
					if(res){
						that.startPage = res.list.length > 0 ? res.list[0]['image'] : ''
					}
				});
		},
		// 轮播图点击
		onBanner(item) {
			var url = item.route
			uni.navigateTo({
				url: url,
				fail() {
					uni.switchTab({
						url: url
					})
				}
			})
		},
		// 轮播图变化
		onSwiperChange(e){
			this.swiperIndex = e.detail.current;
		},
		// 点击搜索
		search(){
			var that = this;
			that.ajax.page = 1;
			that.leftHeight = 0
			that.rightHeight = 0
			that.leftList = []
			that.rightList = []
			that.getList()
		},
		// 图片瀑布流
		// 监听高度变化
		onHeight(height, tag) {
			if (tag == 'left') {
				this.leftHeight += height;
			} else {
				this.rightHeight += height;
			}
		},
		// 组件点击事件
		onClick(index,a,b){
			console.log(this.userData,'***')
			if(!this.uid || this.userData.length == 0){
				this.homeAdvShow = true
			}else{
				uni.navigateTo({
					url: '/pages/home/matchmaker_user_detail/matchmaker_user_detail?authentication_id=' + index.authentication_id + '&a=' + a + '&b=' + b
				})
			}
			
		},
		// 获取数据
		getList() {
			var that = this
			that.$http.get('api/ZhAuthentication/index',{...that.searchData,...that.ajax,'real_name':that.keyword}).then(res => {
					if(res){
						that.addList(res.data)
					}
				});
		},
		addList(res) {
			// 获取到的数据，请注意数据结构
			
			if(!res || res.length < 1){
				this.ajax.loadTxt = '没有更多了';
				return;
			}

			// 左右列表高度的差
			let differ = this.leftHeight - this.rightHeight;
			// 计算差值，用于确定优先插入那一边
			let differVal = 0;
							
			// 初始化左右列表的数据
			let i = differ > 0 ? 1 : 0;
			
			let [left, right] = [
				[],
				[]
			];
			
			
			// 获取插入的方向
			let getDirection = (index)=>{
				/* 左侧高度大于右侧超过 600px 时，则前3条数据都插入到右边 */
				if(differ>= 600 && index < 3){
					differVal = 1;
					return 'right';
				}
				
				/* 右侧高度大于左侧超过 600px 时，则前3条数据都插入到左边 */
				if(differ <= -600 && index < 3){
					differVal = -1;
					return 'left';
				}
				
				/* 左侧高度大于右侧超过 350px 时，则前2条数据都插入到右边 */
				if(differ >= 350 && index < 2){
					return 'right';
				}
				/* 右侧高度大于左侧超过 350px 时，则前2条数据都插入到左边 */
				if(differ <= -350 && index < 2){
					differVal = -1;
					return 'left';
				}
				
				/* 当前数据序号为偶数时，则插入到左边 */
				if ((i+differVal) % 2 == 0) {
					return 'left';
				} else {
					/* 当前数据序号为奇数时，则插入到右边 */
					return 'right';
				}
			}
			
			// 将数据源分为左右两个列表，容错差值请自行根据项目中的数据情况调节
			res.forEach((item, index) => {
				if(getDirection(index) == 'left'){
					//console.log(`差值：${differ},方向：left，序号${index}`)
					left.push(item);
				}else{
					//console.log(`差值：${differ},方向：right，序号${index}`)
					right.push(item);
				}
				i++;
			});
			// 将左右列表的数据插入，第一页时则覆盖
			if(this.ajax.page == 1){
				this.leftList = left;
				this.rightList = right;
				uni.stopPullDownRefresh();
			}else{
				this.leftList = [...this.leftList, ...left];
				this.rightList = [...this.rightList, ...right];
			}

			this.ajax.load = true;
			this.ajax.loadTxt = '上拉加载更多';
			this.ajax.page++;
		},
		// 前往红娘列表
		goHongniang(){
			if(!this.uid || this.userData.length == 0){
				this.homeAdvShow = true
			}else{
				uni.navigateTo({
					url: '/pages/home/matchmaker_list/matchmaker_list'
				})
			}
		},
		//启动广告显示
		showStartAdv(){
			uni.hideTabBar()
			this.isShow = true
			var a = 0;
			var that = this
			var myVar = setInterval(()=>{
				a = --that.i
				if(a <= 0){
					clearInterval(myVar);
					that.isShow = false
					// #ifdef APP-PLUS || H5
					uni.showTabBar({
						animation: true
					})
					// #endif
					uni.setStorageSync('storage_key', 'hello');
				}
			}, 1000);
		},
		// 点击收藏/取消收藏
		collection(i,a,b){
			var that = this
			if(!that.uid){
				uni.showToast({
				    title: '请前往授权登录',
					icon: 'none',
				    duration: 1000
				});
				setTimeout(function() {
					uni.switchTab({
						url: '/pages/my/my'
					});
				}, 1000);
			}else{
				that.$http.post('api/ZhCollection/clickCollection',{
					'marriage_seeking_id': i.authentication_id,
					'release_id': i.u_id
				}).then(res=> {
					uni.showToast({
						title: '成功',
						icon:'none'
					})
					if(a == 'right'){
						if(that.rightList[b].is_collection == 1){
							that.rightList[b].is_collection = 0
						}else{
							that.rightList[b].is_collection = 1
						}
					}else if(a == 'left'){
						if(that.leftList[b].is_collection == 1){
							that.leftList[b].is_collection = 0
						}else{
							that.leftList[b].is_collection = 1
						}
					}
				})
			}
		},
		// 前往筛选页
		goSearch(){
			uni.navigateTo({
				url: '/pages/home/search/search'
			})
		},
		// 获取首页广告
		getHomeAdv(){
			var that = this
			that.$http.get('api/ZhBanner/index',{
				'type':2
			}).then(res=> {
				that.homeAdvData = res.list[0]
			})
		},
		// 关闭首页广告
		guanbi(){
			this.homeAdvShow = false
			// uni.showTabBar({
			// 	animation: true
			// })
		},
		// 获取发布信息
		getMyReleaseData(){
			var that = this
			if(that.uid != ''){
				let uid = that.uid
				that.$http.get('api/ZhAuthentication/getMyReleaseData',{
					uid
				}).then(res => {
					if(res){
						that.userData = res
					}else{
						that.homeAdvShow = true
					}
				});
			}
		},
		// 获取定位
		// getLocation(){
		// 	var that = this
		// 	var QQMapWX = require('../../static/qqmap-wx-jssdk.min.js'),
		// 		qqmapsdk = new QQMapWX({
		// 				'key': 'R3QBZ-2AJKW-QQSRC-RNC3B-BQIF3-BDBUZ' // 必填
		// 			});
					
		// 	wx.getLocation({
		// 	    type: 'gcj02',
		// 	    success :(res) => {
		// 	        console.log(res);//获取到经纬度值
		// 	         qqmapsdk.reverseGeocoder({
		// 	           //位置坐标，默认获取当前位置，非必须参数
		// 	            //Object格式
		// 	              location: {
		// 	                latitude: res.latitude,
		// 	                longitude: res.longitude
		// 	              },
		// 	              //成功后的回调
		// 	               success: r =>{
		// 	                  console.log(r.result.address_component,'****************');
		// 	                  let citty = r.result.address_component.city
		// 	                  that.address = citty
		// 	               }
		// 	      });
			        
		// 	    }
		// 	})
		// }
		
	},
	//页面隐藏
	onHide() {
		// this.searchData = {}
		// this.searchLength = 0
	},
	//页面卸载
	onUnload() {
		console.log('页面卸载*********************')
	},
	//用户点击分享
	onShareAppMessage(e) {
		return this.wxShare();
	}
};
</script>
<style>
	page {
		background-color: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
@import '@/style/mixin.scss';
.banner_swiper_box {
	padding-top: 15upx;
	.banner_swiper {
		height: 220rpx;

		swiper-item {
			box-sizing: border-box;
			display: flex;
			align-items: center;
			.banner_img {
				width: 100%;
				height: 100%;
				border-radius: 24rpx;
				overflow: hidden;
				transform: scale(0.9);
				transition: all 0.4s;
				&.active {
					transform: scale(1);
				}
				image {
					width: 100%;
					height: 100%;
					box-shadow: 0upx 20upx 30upx 0upx rgba(0, 0, 0, 0.1);
					border-radius: 20upx;
				}
			}
		}
	}
}
// 启动页广告开始
.start_adv {
	width: 100%;
	height: 100vh;
	z-index: 10;
}
.adv_img {
	width: 100%;
	height: 100%;
}
.down {
	position: absolute;
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.1);
	color: #000000;
	top: 180rpx;
	right: 30rpx;
	z-index: 3;
	font-size: 28rpx;
	text-align: center;
	line-height: 60rpx;
}
// 启动页广告结束

// 首页广告开始
.home_adv {
	margin: auto;
	.home_adv-img {
		width: 550rpx;
		height: 520rpx;
	}
	.home_adv-tit {
		width: 288rpx;
		height: 70rpx;
		background: #7F5AFF;
		box-shadow: 1rpx 4rpx 0rpx 0rpx #FFC162;
		border-radius: 40rpx;
		font-size: 30rpx;
		font-family: HuXiaoBo-NanShen, HuXiaoBo;
		font-weight: normal;
		color: #FFFFFF;
		line-height: 70rpx;
		text-align: center;
	}
	.home_adv-icon {
		width: 65rpx;
		height: 65rpx;
		margin-top: 100rpx;
	}
}
// 首页广告结束

.video_box {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #000;
	display: flex;
	align-items: center;
	justify-content: center;
	video {
		width: 100%;
	}
}
.flex {
	display: flex;
}
.align-item {
	align-items: center;
}
.j-between {
	justify-content: space-between;
}
.column {
	flex-direction: column;
}
.h-bg {
	width: 100%;
	padding: 196rpx 0 64rpx;
	// #ifdef H5
	padding: 120rpx 0 64rpx;
	// #endif
	.box-item {
		margin: 0 30rpx 30rpx;
		.dingwei {
			width: 32rpx;
			height: 32rpx;
		}
		.chengshi {
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #000000;
			margin: 0 20rpx 0 16rpx;
		}
	}
}
.uni-searchbar__box.data-v-1854464d {
	border: none !important;
}
.main {
	padding: 24rpx 30rpx;
	// #ifdef MP-WEIXIN
	padding: 24rpx 30rpx 200rpx;
	// #endif
	background-color: #fff;
	border-radius: 40rpx 40rpx 0rpx 0rpx;
	margin-top: -40rpx;
	.bt {
		.bt-left {
			.bt-left-img {
				width: 120rpx;
				height: 50rpx;
			}
			.bt-left-txt {
				font-size: 24rpx;
				font-family: PingFang SC;
				font-weight: 300;
				color: #6A6A7E;
				margin: 10rpx 0 0 20rpx;
			}
		}
		.bt-right {
			width: 164rpx;
			height: 56rpx;
			background: #F3EFFF;
			border-radius: 28rpx;
			font-size: 28rpx;
			font-family: PingFang;
			font-weight: 400;
			color: #7F5AFF;
			justify-content: center;
			.bt-right-icon {
				width: 8rpx;
				height: 12rpx;
			}
		}
	}
}

.waterfall-box {
	padding: 20rpx 10rpx;
	box-sizing: border-box;

	>view {
		padding: 0 10rpx;
	}
}

.h-flex-x {
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	justify-content: flex-start;
	align-items: flex-start;
	align-content: flex-start;

	&.h-flex-2 {
		>view {
			width: 50%;
		}
	}
}

.load-txt{
	padding: 0 0 20rpx 0;
	text-align: center;
	color: #999;
	font-size: 24rpx;
}

// 红娘图标
.hn {
	position: fixed;
	bottom: calc(146rpx + env(safe-area-inset-bottom));
	// #ifdef H5
	bottom: 140rpx;
	// #endif
	right: 30rpx;
	width: 160rpx;
	height: 168rpx;
	image {
		width: 100%;
		height: 100%;
	}
}
</style>
